<?php
/**
 * Created by PhpStorm.
 * User: fengyan
 * Date: 2017/8/27
 * Time: 上午1:06
 */

namespace App\Http\Controllers\Admin;

use App\Models;
use App\Repositories;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AdminUserController extends AdminController
{
    /**
     * 初始化操作
     * UserController constructor.
     */
    public function __construct()
    {
        parent::__construct();

        $this->setTemplatePrefix(config('admin.systems.template_prefix', 'admin.').'admin_user.');
    }

    /**
     * 列表页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            return $this->getServiceRepository()->getPaginateData()->toJson();
        }

        $data = $this->getServiceRepository()->getPaginateData();

        return $this->fetch('index', ['data'=>$data]);
    }

    /**
     * 获取当前控制器服务仓库对象
     * @return Repositories\Admin\UserRepository
     */
    public function getServiceRepository() : Repositories\Admin\UserRepository
    {
        if (!($this->serviceRepository instanceof Repositories\Admin\UserRepository)) {
            $this->serviceRepository = new Repositories\Admin\UserRepository();
        }

        return $this->serviceRepository;
    }

    public function edit(Request $request)
    {
        if (strtolower($request->method()) !== 'post') {
            $id = $request->route('id', 0);

            $detail = $this->getServiceRepository()->getSelectModel();
            $action = 'add';
            $roleIdList = [];
            if (!empty($id)) {
                $detail = $this->getServiceRepository()->getDetailById($id);
                $action = 'edit';
                $roleIdList = DB::table('admin_role_user')->where('user_id', '=', $id)->pluck('role_id')->toArray();
            }

            $roleList = (new Repositories\Admin\RoleRepository())->getList();

            return $this->fetch('edit', [
                'metaTitle' => '更新用户信息',
                'postUrl'   => get_admin_url('admin_user/edit'),
                'detail'    => $detail,
                'action'    => $action,
                'roleList'  => $roleList,
                'roleIdList'=> $roleIdList,
            ]);
        }

        $info = $request->input('info', []);

        $action = $request->input('action', 'add');
        if (empty($info['password'])) {
            unset($info['password']);
        } else {
            $info['password'] = bcrypt($info['password']);
        }

        $model = $this->getServiceRepository()->save($info, $action);
        if ($action == 'edit') {
            DB::table('admin_role_user')->where('user_id', '=', $model->id)->delete();
        }

        $roleIds = $request->input('role_id', []);

        $roleIds = is_array($roleIds) ? $roleIds : explode(',', $roleIds);

        $roleIds = array_values($roleIds);

        foreach ($roleIds as $roleId) {
            $model->roles()->attach($roleId); // id only
        }

        return $this->success('保存成功');
    }
}